package com.zjw.zy.coreui.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.zjw.zy.R
import kotlin.math.min

class RecorderButton : View {


    private var mListener: ModeListener? = null

    //0,1 休闲、录制 两种模式
    private var mMode: Int = MODE_FREE

    companion object {

        //1 << 0
        const val MODE_FREE = 1

        // ~MODE_FREE
        const val MODE_RECORDER = 2
    }

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }


    override fun draw(canvas: Canvas?) {
        canvas?.apply {

            val height = measuredHeight.toFloat()
            val width = measuredWidth.toFloat()
            val length = min(height, width)
            val paint = Paint()

//            paint.style = Paint.Style.STROKE
//            paint.color = Color.BLUE
//            this.drawRect(0f, 0f, width, height, paint)

            //外围
            paint.style = Paint.Style.STROKE
            paint.color = resources.getColor(R.color.recorder_button_out_color)
            paint.strokeWidth = length / 15
            this.drawCircle(width / 2, height / 2, length / 3, paint)


            paint.style = Paint.Style.FILL
            paint.color = resources.getColor(R.color.recorder_button_color)
            if (mMode == MODE_FREE) {
                this.drawCircle(width / 2, height / 2, length / 3 - 30, paint)
            } else {
                this.drawRect(length / 3, length / 3, length / 3 * 2, length / 3 * 2, paint)
            }

            return@apply
        }
        super.draw(canvas)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        this.setOnClickListener {
            mMode = if (mMode == MODE_RECORDER) {
                MODE_FREE
            } else {
                MODE_RECORDER
            }
            mListener?.onModeChange(mMode)
            invalidate()
        }
    }

    fun bindListener(listener: ModeListener) {
        mListener = listener
    }


    interface ModeListener {
        fun onModeChange(mode: Int)
    }
}